// pages/edit-account/editAccount.js
import Ajax from '../../common/Ajax';
import citys from '../../common/citys';
import moment from '../../common/moment';

let sessionId = wx.getStorageSync('sessionId');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: "",
        accountName: "",
        companyLoading: false,
        companyColumns: [],
        companyShow: false,
        company: "",
        designCompanyName: "",
        convenTypeShow: false,
        convenType: "",
        convenLoading: false,
        convenColumns: [],
        areaList: citys,
        joinConShow: false,
        makeLocalShow: false,
        makeLocal: "",
        detailLoc: "",
        startTimeShow: false,
        endTimeShow: false,
        currentStart: '',
        currentEnd: "",
        accountInfo: {},
        makeAddressInfo: "",
        area: "",
        quotedPrice: "",
        allSalary: "",
        settledSalary: "",
        fileList: [],
        sign: "",
        exhibitionTypeName: "",
    },

     /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            id: options.id,
            sign: options.sign
        })
        if(options.sign === "edit") {
            wx.showLoading({
              title: '查询中...',
            })
            Ajax.get(`/companyAccounts/findById?companyAccountId=${options.id}`, {}, sessionId)
                .then(res => {
                    res.data.makeStartTime = moment(res.data.makeStartTime).format("YYYY-MM-DD")
                    res.data.makeEndTime = moment(res.data.makeEndTime).format("YYYY-MM-DD")
                    res.data.makeStart = new Date(res.data.makeStartTime).getTime()
                    res.data.makeEnd = new Date(res.data.makeEndTime).getTime()
                    let arr = [];
                    let json = {};
                    res.data.fileUrlList.forEach(item => {
                        json.url = item;
                        arr.push(json);
                    })
                    this.setData({accountInfo: res.data, fileList: arr})
                })
                .catch(err => {
                    throw err;
                })
                .finally(() => {
                    wx.hideLoading()
                })
        }
    },

    handleChange: function(child, val) {
        const { accountInfo } = this.data;
        accountInfo[child] = val;
        this.setData({
            accountInfo,
        })
    },

    onChange: function(e) {
        const { id } = e.currentTarget
        let val = e.detail;
        if(id === "accountName") {
            this.setData({
                accountName: val
            }, () => {
                this.handleChange("accountName", val)
            })
        } else if(id === "design") {
            this.setData({
                designCompanyName: val
            }, () => {
                this.handleChange("designCompanyName", val)
            })
        } else if(id === "detailLoc") {
            this.setData({
                makeAddressInfo: val
            }, () => {
                this.handleChange("makeAddressInfo", val)
            })
        } else if(id === "area") {
            this.setData({
                area: val
            }, () => {
                this.handleChange("area", val)
            })
        } else if(id === "quotedPrice") {
            this.setData({
                quotedPrice: val
            }, () => {
                this.handleChange("quotedPrice", val)
            })
        } else if(id === "allSalary") {
            this.setData({
                allSalary: val
            }, () => {
                this.handleChange("allSalary", val)
            })
        } else if(id === "settledSalary") {
            this.setData({
                settledSalary: val
            }, () => {
                this.handleChange("settledSalary", val)
            })
        }
    },

    uploadPhoto: function(e) {
        const { file } = e.detail;
        Ajax.upload("/imgs/upload", {filePath: file.path}, sessionId)
            .then(res => {
                res = JSON.parse(res);
                if(res.code === "0") {
                    const { fileList } = this.data;
                    let json = {};
                    json.url = res.data.picUrl;
                    fileList.push(json);
                    this.setData({fileList}, () => {
                        let arr = [];
                        fileList.forEach(item => {
                            arr.push(item.url)
                        })
                        this.handleChange("fileUrlList", arr)
                    })
                }
            })
    },

    chooseTime: function(e) {
        const { id } = e.currentTarget
        if(id === "start") {
            this.setData({startTimeShow: true})
        } else if(id === "end") {
            this.setData({endTimeShow: true})
        }
    },

    timeConfirm: function(e) {
        const { id } = e.currentTarget
        console.log(e);
        const time = moment(e.detail).format("YYYY-MM-DD")
        console.log(time);
        if(id === "start") {
            this.setData({startTimeShow: false, currentStart: time,  }, () => {
                this.handleChange("makeStartTime", e.timeStamp)
            })
        } else if(id === "end") {
            this.setData({endTimeShow: false, currentEnd: time,  }, () => {
                this.handleChange("makeEndTime", e.timeStamp)
            })
        }
    },
    chooseColumn: function(e) {
        const { id } = e.currentTarget
        if(id === "company") {
            this.setData({companyLoading: true, companyShow: true})
            Ajax.get("/userCompanys/findListByUserId", {}, sessionId)
                .then(res => {
                    res.data.forEach(item => {
                        item.text = item.companyName
                    })
                    this.setData({
                        companyColumns: res.data
                    })
                })
                .catch(err => {
                    throw err
                })
                .finally(() => {
                    this.setData({companyLoading: false})
                })
        } else if(id === "convenType") {
            this.setData({ convenLoading: true, convenTypeShow: true })
            Ajax.get("/exhibitionTypes/findALL", {}, sessionId)
                .then(res => {
                    res.data.forEach(item => {
                        item.text = item.typeName
                    })
                    this.setData({
                        convenColumns: res.data
                    })
                })
                .catch(err => {
                    throw err
                })
                .finally(() => {
                    this.setData({convenLoading: false})
                })
        }
    },

    setCompany: function(e) {
        // const { id } = e.currentTarget;
        const company = e.detail.value;
        this.setData({
            workCompanyName: company.text, 
            companyShow: false
        }, () => {
            this.handleChange("workCompanyName", company.text)
            this.handleChange("userCompanyId", company.id)
        })
    },

    setLocal: function(e) {
        const { id } = e.currentTarget;
        const result = this.joinLoca(e);
        if(id === "location") {
            this.setData({
                location: result,
                joinConShow: false,
            }, () => {
                this.handleChange("exhibitionCounty", e.detail.values[2].code)
            })
        } else if(id === "makeLocal") {
            this.setData({
                makeLocal: result,
                makeLocalShow: false,
            }, () => {
                this.handleChange("makeCounty", e.detail.values[2].code)
            })
        }
    },
    setConven: function(e) {
        // const { id } = e.currentTarget;
        const conven = e.detail.value;
        this.setData({
            exhibitionTypeName: conven.text, 
            convenTypeShow: false
        }, () => {
            this.handleChange("exhibitionTypeName", conven.text)
            this.handleChange("exhibitionTypeId", conven.id)
        })
    },

    chooseLoc: function(e) {
        const { id } = e.currentTarget;
        if(id === "location") {
            this.setData({joinConShow: true })
        } else if(id === "makeLocal") {
            this.setData({makeLocalShow: true})
        }
    },

    /**
     * 
     * 拼接地点函数
     */
    joinLoca: function (e) {
        let completeName = "";
        let param = e.detail.values;
        param.forEach(item => {
            completeName += `${item.name} `
        })
        return completeName;
    },

    toSave: function() {
        const { sign, accountInfo } = this.data;
        wx.showLoading({
            title: '进行中...',
          })
        if(sign === "edit") {
            Ajax.post("/companyAccounts/updateCompanyAccount", accountInfo, sessionId)
                .then(res => {
                    console.log(res);
                    if(res.code === "0") {
                        wx.navigateTo({
                          url: '../company-account/companyAccount',
                        })
                    }
                })
                .catch(err => {
                    throw err;
                })
                .finally(() => {
                    wx.hideLoading();
                })
        } else {
            Ajax.post("/companyAccounts/addCompanyAccount", accountInfo, sessionId)
                .then(res => {
                    console.log(res);
                    if(res.code === "0") {
                        wx.navigateTo({
                        url: '../company-account/companyAccount',
                        })
                    }
                })
                .catch(err => {
                    throw err;
                })
                .finally(() => {
                    wx.hideLoading();
                })
        }
    },
})